package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//过滤器声明拦截的路径
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

        String[] urls=new String[] {
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断请求中是否包含可以放行的路径
        boolean result = doFilter(urls, uri);
        if (result) {
            filterChain.doFilter(request,response);
            return;
        }
        //判断用户是否已经登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            //通过ThreadLoad传入id
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            //通过ThreadLoad传入id
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    //判断是否放行uri
    public boolean doFilter(String[] urls,String uri){
        for (String url : urls) {
            boolean result = PATH_MATCHER.match(url, uri);
            if (result) {
                return true;
            }
        }
        return false;
    }
}
